<script setup lang="ts">
import {onMounted, ref, onBeforeUpdate, onUpdated} from "vue";
import axios from "axios";
import {loginUser, ServerHost, orderStatusEnum} from "@/main";
import {ElMessageBox, ElNotification} from "element-plus";
import dayjs from "dayjs";
import {downloadImg} from "@/utils";

const myOrderList = ref({
  goodsOrderList: [{
    id: "",
    goodsId: "",
    buyerId: "",
    buyPriceCent: 0,
    buyNum: 1,
    tel: "",
    province: "",
    city: "",
    districtAndCounty: "",
    address: "",
    receiver: "",
    buyTime: new Date(),
    shippingTime: new Date(),
    finishTime: new Date(),
    status: 0,
    payMethod: "",
    expressNum: "",
    goods: {
      id: "",
      name: "",
      priceCent: 0,
      img: "",
      introduction: "",
      sellerId: "",
      inventory: 1,
      sales: 0,
      addTime: new Date(),
      type: "",
    }
  }],
  goodsList: [{}],
  result: ""
})
const isLoadingList = ref(true)

// 懒加载列表
const observerDiv = ref(null)
const hasLoad = ref(false)
onMounted(() => {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        if (!hasLoad.value) {
          loadList()
        }
      }
    });
  });
  observer.observe(observerDiv.value);
})

const loadList = () => {
  axios.get(`${ServerHost}/getBuyerGoodsOrder?buyerId=${loginUser.value.id}`)
      .then((res) => {
        if (res.status === 200 && res.data.result === "ok") {
          myOrderList.value = res.data;
          // 绑定对应的商品信息
          myOrderList.value.goodsOrderList.forEach((myOrder, i) => {
            myOrder.goods = myOrderList.value.goodsList.find((goods) => goods.id === myOrder.goodsId) as any
          })
          hasLoad.value = true
          isLoadingList.value = false
        } else {
          ElNotification({
            title: '用户订单获取失败',
            type: 'error',
            position: 'bottom-right',
          })
        }
      })
}

// 懒加载商品图片
const goodsImgItemRefs = ref([]);
const setGoodsImgRef = (el: any) => {
  if (el) {
    goodsImgItemRefs.value.push(el);
  }
}

onBeforeUpdate(() => {
  goodsImgItemRefs.value = [];
});

const goodHasLoadImgIdList = ref([]); // 已经加载过图片的商品id列表
onUpdated(() => {
  goodsImgItemRefs.value.forEach((item: any) => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const goodId = item.getAttribute('data-id');
          if (!goodHasLoadImgIdList.value.includes(goodId)) {
            goodHasLoadImgIdList.value.push(goodId);
            const goods = myOrderList.value.goodsList.find(goods => goods.id == goodId)
            //   加载图片
            downloadImg(goods.img, "goodsImg/")
                .then(res => {
                  if (res.status === 200) {
                    const type = 'image/png'
                    const blob = new Blob([res.data], {type: type})
                    const imgFile = new File([blob], goods.img, {type: type})
                    goods.imgUrl = URL.createObjectURL(imgFile)
                    console.log(goods)
                  }
                })
          }

        }
      });
    });
    observer.observe(item);
  });
});

const onClickStatus = (order: {}) => {
  console.log(order);
  switch (order.status) {
    case 0:
      ElNotification({
        title: '等待卖家发货',
        type: 'warning',
        position: 'bottom-right',
      })
      break
    case 1:
      ElMessageBox.confirm(
          '请确保已收到货物并检测无误再确认收货',
          '确认收货',
          {
            confirmButtonText: '确认收货',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {
            axios.post(`${ServerHost}/updateOrderStatus?id=${order.id}&to=2`)
                .then((res) => {
                  if (res.status === 200 && res.data.result === "ok") {
                    ElNotification({
                      title: '收货成功',
                      type: 'success',
                      position: 'bottom-right',
                    })
                    loadList()
                  } else {
                    ElNotification({
                      title: '收货失败',
                      type: 'error',
                      position: 'bottom-right',
                    })
                  }
                })
          })
          .catch(() => {
            console.log("用户取消了收货");
          })
  }
}

</script>

<template>
  <div ref="observerDiv"/>
  <p class="m-4 text-center">我的订单</p>
  <div class="flex flex-col gap-2 m-2">
    <div v-for="order in myOrderList.goodsOrderList" :ref="setGoodsImgRef" :data-id="order.goods.id">
      <el-card class="order-card m-auto">
        <div class="flex flex-row justify-between items-center gap-2">
          <!--     左侧商品图片     -->
          <router-link :to="'/goods/' + order.goodsId" target="_blank">
            <img class="goods-img"
                 :src="order.goods.imgUrl"
                 alt="商品图片">
            <!--     右侧信息     -->
          </router-link>
          <div class="flex flex-col flex-1">
            <!--      右侧上方信息      -->
            <div class="flex flex-1 gap-2">
              <div class="flex flex-col flex-1 gap-0.5">
                <p class="name">{{ order.goods.name }}</p>
                <p class="id">订单号：{{ order.id.split('-')[4] }}</p>
                <el-button @click="onClickStatus(order)" class="order-status" effect="plain">
                  {{ Object.keys(orderStatusEnum)[order.status] }}
                </el-button>
              </div>
              <div class="flex flex-col text-right gap-0.5">
                <p><span class="price-sign">￥</span>{{ (order.buyPriceCent / 100).toFixed(2) }}</p>
                <p>x{{ order.buyNum }}</p>
                <p>总计<span class="price-sign">￥</span>{{ (order.buyNum * (order.buyPriceCent / 100)).toFixed(2) }}</p>
              </div>
            </div>

            <!--      右侧下方信息      -->
            <div class="flex flex-col gap-1 mt-4">
              <el-timeline style="max-width: 600px">
                <el-timeline-item type="info" :hide-timestamp="true" :timestamp="order.buyTime" placement="top">
                  <p>{{ dayjs(order.buyTime).format('YYYY/MM/DD HH:mm:ss') }}</p>
                  <p>已提交订单，等待卖家处理</p>
                </el-timeline-item>
                <el-timeline-item type="success" :hide-timestamp="true" v-if="order.status > 0" :timestamp="order.shippingTime"
                                  placement="top">
                  <p>{{ dayjs(order.shippingTime).format('YYYY/MM/DD HH:mm:ss') }}</p>
                  <p>卖家已发货</p>
                  <p class="order-express-num">快递单号：{{ order.expressNum }}</p>
                </el-timeline-item>
                <el-timeline-item type="primary" :hide-timestamp="true" v-if="order.status > 1" :timestamp="order.finishTime"
                                  placement="top">
                  <p>{{ dayjs(order.finishTime).format('YYYY/MM/DD HH:mm:ss') }}</p>
                  <p>已确认收货</p>
                </el-timeline-item>
              </el-timeline>
              <el-button>收货信息</el-button>
<!--              <el-tag>{{ dayjs(order.buyTime).format('YYYY/MM/DD HH:mm:ss') }} 提交订单</el-tag>-->
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<style scoped lang="scss">
.order-card {
  width: 600px;
}

.goods-img {
  width: 200px;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.name {
  font-family: "思源宋体 Heavy", serif;
  font-size: 1.2rem;
  color: var(--el-color-primary);
}

.id {
  font-size: 0.7rem;
  color: var(--el-color-info);
}

.order-status {
  //width: fit-content;
}

.price-sign, .order-shipping-time, .order-express-num, .order-finish-time {
  font-size: 0.8rem;
}

</style>
